#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/26 22:01
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : ser_token.py
# @Software: PyCharm
# @Desc    :

from rest_framework import serializers
from common.models import Token


class TokenSerializer(serializers.ModelSerializer):
    # 显式定义时间字段并指定格式
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", read_only=True)
    expires_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")

    class Meta:
        model = Token
        fields = "__all__"
        read_only_fields = ["access_token", "create_time", "update_time"]  # 自动生成的字段不可修改

    def validate_name(self, value):
        """
        检查name是否已存在（排除当前编辑的实例）
        """
        # 获取当前实例（编辑时存在，新增时为None）
        instance = self.instance

        # 查询已存在的记录（排除已删除和压测数据）
        queryset = Token.objects.filter(name=value, is_delete=0, pt_flag=0)

        # 如果是编辑操作，排除当前记录
        if instance is not None:
            queryset = queryset.exclude(id=instance.id)

        if queryset.exists():
            raise serializers.ValidationError(f"Token名称「{value}」已被占用，请更换！")

        return value

    def validate_allowed_ips(self, value):
        """验证IP格式（逗号分隔）"""
        if value != "*":
            ips = value.split(",")
            for ip in ips:
                if not ip.strip():  # 防止空字符串
                    raise serializers.ValidationError("IP地址不能为空")
        return value
